/**
 * 
 */
package org.dce.screencapturer;

import java.awt.Cursor;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import org.dce.screencapturer.actions.drawing.InsertObjectAction;
import org.dce.screencapturer.objects.DrawingObject;

public class InsertionHandler 
	implements MouseListener, 
		MouseMotionListener, 
		KeyListener{
	
	private InsertObjectAction insertAction;
	private Drawing drawingArea;
	private Point firstPoint;
	private DrawingObject objectToBeInserted;
	private boolean finished = false;

	public InsertionHandler(Drawing drawingArea, InsertObjectAction action){
		this.drawingArea = drawingArea;
		this.insertAction = action;
	}

	public void start() {
		drawingArea.addMouseListener(this);
		drawingArea.addMouseMotionListener(this);
		drawingArea.addKeyListener(this);
		drawingArea.setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
	}

	private void finish() {
		drawingArea.removeMouseListener(this);
		drawingArea.removeMouseMotionListener(this);
		drawingArea.removeKeyListener(this);
		drawingArea.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
		finished = true;
	}

	public void cancel() {
		if (objectToBeInserted != null){
			drawingArea.remove(objectToBeInserted);
		}
		finish();
	}

	public boolean isFinished(){
		return finished;
	}
	
	@Override
	public void mousePressed(MouseEvent e) {
		
		if (firstPoint == null){
			firstPoint = e.getPoint();
			
			objectToBeInserted = insertAction.getInsertedObject();
			objectToBeInserted.insertionStarted(firstPoint);
			objectToBeInserted.setLocation(firstPoint);
			drawingArea.add(objectToBeInserted,0);
		}
	}
	public void mouseReleased(MouseEvent e) {
		if (firstPoint != null){
			Point secondPoint = e.getPoint();
			
			if (secondPoint.distance(firstPoint) < 2){
				cancel();
			} else {
				objectToBeInserted.insertionDone(secondPoint);
				finish();
			}
		}
	}
	
	@Override
	public void mouseMoved(MouseEvent e) {
		selectSecondPoint(e);
	}

	@Override
	public void mouseDragged(MouseEvent e) {
		selectSecondPoint(e);
	}

	private void selectSecondPoint(MouseEvent e) {
		if (firstPoint != null){
			objectToBeInserted.updateInsertionProgress(e.getPoint());
		}
	}
	
	@Override
	public void keyPressed(KeyEvent e) {
		if (e.getKeyCode() == KeyEvent.VK_ESCAPE){
			cancel();
		}
	}

	public void mouseClicked(MouseEvent e) {}
	public void mouseEntered(MouseEvent e) {}
	public void mouseExited(MouseEvent e) {}
	public void keyReleased(KeyEvent e) {}
	public void keyTyped(KeyEvent e) {}
}